package com.efounder.utils;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import com.efounder.thirdpartycomps.R;
import com.utilcode.util.JFStringUtil;
import com.utilcode.util.ToastUtils;

/**
 * 限制输入数字的TextWatcher
 * 设置 .setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
 * @author will
 */
public class NumberTextWatcher implements TextWatcher {

    private EditText editText;

    public NumberTextWatcher(EditText editText) {
        this.editText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
//输入不为"",或者输入以.开头
        if (!s.toString().equals("") || s.toString().startsWith(".")) {
            //输入的不是数字，那么置为“”
            if (!JFStringUtil.inputIsNumber(s.toString())) {
                ToastUtils.showShort(R.string.common_text_input_correct_amount);
                editText.setText("");
            } else {
                String amount = editText.getText().toString();
                //输入以.开头，补0
                if (amount.startsWith(".")) {
                    amount = "0".concat(amount);
                    editText.setText(amount);
                    editText.setSelection(editText.getText().length());
                }
            }
        }
    }
}
